/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.sales;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import main.ServicesList;
import model.sales.SalesInit;
import utility.Constants;
import utility.NameValueList;
import utility.StringUtils;
import utility.com.ColumnResizer;
import view.OfficeFrame;
import view.RekapTemplate;
import view.purchasing.OrderFrm;

/**
 *
 * @author Lalugina
 */
public class SalesInitListFrm extends RekapTemplate {
    private final int COL_NO = 0;
    private final int COL_STAR_DATE = 1;
    private final int COL_CLOSE_DATE = 2;
    private final int COL_PC = 3;
    private final int COL_USER = 4;
    private final int COL_SHIFT = 5;
    private final int COL_MODAL = 6;
    
    DefaultTableCellRenderer rightCellRender = new DefaultTableCellRenderer();
    
    List<SalesInit> initList;
    SalesInitListTM tableModel;
    
    private Object oldValue, newValue;
    private ItemListener comboboxListener = new ComboboxListener();
    
    public SalesInitListFrm() {
        initComponents();
        initComponentsRole();
    }

    class ActionKeyListener implements KeyListener {
        @Override public void keyTyped(KeyEvent e) {} 
        @Override public void keyReleased(KeyEvent e) {}
        
        @Override public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) { 
                    
                case KeyEvent.VK_ENTER: 
                    if ("JTextField".equals(e.getSource().getClass().getSimpleName())) {
                        Component componen = (Component) e.getSource(); 
                        newValue = ((JTextField) componen).getText();
                        
                         if (!newValue.equals(oldValue)) { loadData(); }
                    }
                break;      
            }
        }
    }
    
    class ActionFocusGained implements FocusListener {
        @Override public void focusGained(FocusEvent e) { 
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { oldValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { oldValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { oldValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
        }
        
        @Override public void focusLost(FocusEvent e) {
            Component componen = (Component) e.getSource(); 
            if (componen instanceof JTextField) { newValue = ((JTextField) componen).getText();
            }else if (componen instanceof JComboBox) { newValue = ((JComboBox) componen).getSelectedIndex();
            }else if (componen instanceof JCheckBox) { newValue = ((JCheckBox) componen).isSelected();
            }else if (componen instanceof JTextArea) { oldValue = ((JTextArea) componen).getText(); }
        }
    }

    class ComboboxListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange()==ItemEvent.SELECTED) {
                loadData();
            }
        }
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnNew = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnLoad = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        dtpAwal = new com.toedter.calendar.JDateChooser();
        dtpAkhir = new com.toedter.calendar.JDateChooser();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtUser = new javax.swing.JTextField();
        cmbStatus = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setMaximumSize(new java.awt.Dimension(32767, 20));
        jToolBar1.setSize(this.getWidth(), 50);

        btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_add.png"))); // NOI18N
        btnNew.setText("Tambah");
        btnNew.setFocusable(false);
        btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnNew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewActionPerformed(evt);
            }
        });
        jToolBar1.add(btnNew);

        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit.png"))); // NOI18N
        btnEdit.setText("Edit");
        btnEdit.setFocusable(false);
        btnEdit.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEdit.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        jToolBar1.add(btnEdit);

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_remove.png"))); // NOI18N
        btnDelete.setText("Hapus");
        btnDelete.setFocusable(false);
        btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnDelete);

        btnLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/reload.png"))); // NOI18N
        btnLoad.setText("Load");
        btnLoad.setFocusable(false);
        btnLoad.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });
        jToolBar1.add(btnLoad);

        btnReset.setText("Reset");
        btnReset.setFocusable(false);
        btnReset.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnReset.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });
        jToolBar1.add(btnReset);

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/print.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setFocusable(false);
        btnPrint.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnPrint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnPrint);

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        dtpAwal.setName("dtpAwal"); // NOI18N

        dtpAkhir.setName("dtpAkhir"); // NOI18N

        jLabel1.setText("Periode :");

        jLabel2.setText("Sampai :");

        txtUser.setName("txtUser"); // NOI18N

        cmbStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Semua", "Open", "Posted", "Received", "Closed" }));
        cmbStatus.setName("cmbStatus"); // NOI18N

        jLabel3.setText("Status :");

        jLabel4.setText("Operator :");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dtpAkhir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(dtpAwal, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtUser)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(cmbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 138, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(dtpAwal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3))
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dtpAkhir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setTopComponent(jPanel1);

        grid.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        grid.setName("grid"); // NOI18N
        jScrollPane1.setViewportView(grid);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 491, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 333, Short.MAX_VALUE)
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane1))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
        insertGrid();
    }//GEN-LAST:event_btnNewActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        updateGrid();
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        loadData();
    }//GEN-LAST:event_btnLoadActionPerformed

    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        initFilter();
    }//GEN-LAST:event_btnResetActionPerformed
      
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnNew;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnReset;
    private javax.swing.JComboBox cmbStatus;
    private com.toedter.calendar.JDateChooser dtpAkhir;
    private com.toedter.calendar.JDateChooser dtpAwal;
    private javax.swing.JTable grid;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtUser;
    // End of variables declaration//GEN-END:variables

    @Override
    public void execute(boolean withVisible, int id) {
        setLocationRelativeTo(null);
        initForm();
        if (withVisible) { setVisible(true); }
    }

    @Override
    protected void initGrid() {
        tableModel = new SalesInitListTM(initList);
        grid.setModel(tableModel);
        grid.getColumnModel().getColumn(COL_NO).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_LTIME).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_TOP).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_SUBTOT).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_DISKON).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_PPN).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_TOTAL).setCellRenderer(rightCellRender);
//                        
//        grid.getColumnModel().getColumn(COL_NO).setCellRenderer(rightCellRender);
//        grid.getColumnModel().getColumn(COL_NO).setMaxWidth(60);
//        grid.getColumnModel().getColumn(COL_LTIME).setMaxWidth(40);
//        grid.getColumnModel().getColumn(COL_DIV).setMaxWidth(40);
//        grid.getColumnModel().getColumn(COL_TOP).setMaxWidth(30);
//        grid.getColumnModel().getColumn(COL_SUBTOT).setMaxWidth(120);
//        grid.getColumnModel().getColumn(COL_DISKON).setMaxWidth(120);
//        grid.getColumnModel().getColumn(COL_PPN).setMaxWidth(120);
//        grid.getColumnModel().getColumn(COL_TOTAL).setMaxWidth(150);
//        grid.getColumnModel().getColumn(COL_DATE).setMaxWidth(90);
//        grid.getColumnModel().getColumn(COL_NUM).setMaxWidth(100);
//                        
//        grid.getColumnModel().getColumn(COL_NO).setMinWidth(30);
//        grid.getColumnModel().getColumn(COL_LTIME).setMinWidth(40);
//        grid.getColumnModel().getColumn(COL_DIV).setMinWidth(30);
//        grid.getColumnModel().getColumn(COL_TOP).setMinWidth(30);
//        grid.getColumnModel().getColumn(COL_SUBTOT).setMinWidth(100);
//        grid.getColumnModel().getColumn(COL_DISKON).setMinWidth(100);
//        grid.getColumnModel().getColumn(COL_PPN).setMinWidth(100);
//        grid.getColumnModel().getColumn(COL_TOTAL).setMinWidth(120);
//        grid.getColumnModel().getColumn(COL_DATE).setMinWidth(90);
//        grid.getColumnModel().getColumn(COL_NUM).setMinWidth(90);
        
        setTableLookStyle();
        grid.setGridColor(Color.LIGHT_GRAY);
    }

    @Override
    protected void initFilter() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1);
        
        dtpAwal.setDate(cal.getTime());
        dtpAkhir.setDate(new Date());
        txtUser.setText("");
        cmbStatus.setSelectedIndex(0);
        
    }
    
    protected Map<NameValueList, Object> getFilter(){
        Map<NameValueList, Object> params = new HashMap<>();
        
        params.put(new NameValueList("date(salesInit.transDate)", Constants.OPERATOR_GTE), StringUtils.truncDate(dtpAwal.getDate()));
        params.put(new NameValueList("date(salesInit.transDate)", Constants.OPERATOR_LTE), StringUtils.truncDate(dtpAkhir.getDate()));
        
//        if (supplier!=null) {
//            params.put(new NameValueList("salesInit.userInserted", Constants.OPERATOR_EQUAL), supplier.getId()); 
//        }
        
//        switch (cmbStatus.getSelectedIndex()) {
//            case 1: params.put(new NameValueList("mst.statusId", Constants.OPERATOR_EQUAL), Constants.STATUS_TRANS_OPEN); break;
//            case 2: params.put(new NameValueList("mst.statusId", Constants.OPERATOR_EQUAL), Constants.STATUS_TRANS_POSTED); break;
//            case 3: params.put(new NameValueList("mst.statusId", Constants.OPERATOR_EQUAL), Constants.STATUS_TRANS_RECEIVED); break;
//            case 4: params.put(new NameValueList("mst.statusId", Constants.OPERATOR_EQUAL), Constants.STATUS_TRANS_CLOSED); break;
//         }
        
         params.put(new NameValueList(null, Constants.OPERATOR_ORDERBY), "salesInit.transDate"); 
        
        return params;
    }

    @Override
    protected void loadData() {
        initList = ServicesList.getSalesInitService().getAll(0, 100000, getFilter());
        tableModel.clear();
        tableModel.add(initList);

        ColumnResizer.adjustColumnPreferredWidths(grid);
    }

    @Override
    protected void updateGrid() {
        int row = grid.getSelectedRow();
        if (row > -1) {
            if(initList.get(row) != null) {
                long id = initList.get(row).getId();
                OrderFrm orderFrm = new OrderFrm();
                orderFrm.execute2(false, id);
                ((OfficeFrame)ServicesList.MAIN_FRAME).createTab("New Purchase Order", orderFrm.getContentPane());
            }
        }
    }

    @Override
    protected void insertGrid() {
        long idparam=0;
        long id = new SalesInitFrm().execute(idparam);
        if (id>0) {
           // Promo insertedData = ServicesList.getPromoService().getPromo(id);
           // tableModel.add(insertedData);
        }
    }

    private void initForm () {
        initList = new ArrayList<>();
        initFilter();
        initGrid();
    }
    
    private void initComponentsRole () {
        rightCellRender.setHorizontalAlignment(SwingConstants.RIGHT);
        txtUser.addKeyListener(new ActionKeyListener());
        txtUser.addFocusListener(new ActionFocusGained());
        cmbStatus.addItemListener(comboboxListener); 
    }
   
    private void setTableLookStyle() {
        //look style
        final TableCellRenderer header = grid.getTableHeader().getDefaultRenderer();
        grid.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel lbl = (JLabel) header.getTableCellRendererComponent(table, 
                      value, isSelected, hasFocus, row, column);
                lbl.setBorder(BorderFactory.createEmptyBorder(5,1,5,1));   

//                switch (column) {
//                    case COL_NUM: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
//                    case COL_DATE: lbl.setHorizontalAlignment(SwingConstants.LEFT); break; 
//                    case COL_SUPPLIER: lbl.setHorizontalAlignment(SwingConstants.LEFT); break;
//                    case COL_DIV: lbl.setHorizontalAlignment(SwingConstants.CENTER); break;
//                    default: lbl.setHorizontalAlignment(SwingConstants.RIGHT); break;   
//                }
                lbl.setForeground(Color.WHITE);
                lbl.setBackground(Color.DARK_GRAY);
                return lbl;
            }
        });
        
    }
    
}
